<template>
  <div class="side" ref="side">
    <span class="text">欢迎光临</span>
    <i class="iconfont icon-fold"></i>
    <span class="back" ref="back" @click="back">返回顶部</span>
  </div>
</template>

<script>
export default {
  methods: {
    setSide () {
      if (window.pageYOffset >= 220) {
        this.$nextTick(() => {
          this.$refs.side.style.position = 'fixed'
          this.$refs.side.style.top = 80 + 'px'
          this.$refs.side.style.backgroundColor = 'white'
          this.$refs.side.firstElementChild.style.borderRadius = 0
          this.$refs.back.style.display = 'block'
          this.$refs.back.previousSibling.style.display = 'block'
        })
      } else {
        this.$nextTick(() => {
          this.$refs.side.style.position = 'absolute'
          this.$refs.side.style.top = 300 + 'px'
          this.$refs.side.style.backgroundColor = '#eae8eb'
          this.$refs.side.firstElementChild.style.borderRadius = 20 + 'px'
          this.$refs.back.style.display = 'none'
          this.$refs.back.previousSibling.style.display = 'none'
        })
      }
    },
    back () {
      let step = 0
      const interval = setInterval(() => {
        if (document.documentElement.scrollTop <= 0) {
          clearInterval(interval)
          return
        }
        step += 10
        document.documentElement.scrollTop -= step
      }, 20)
    }
  },
  mounted () {
    window.addEventListener('scroll', this.setSide)
  }
}
</script>

<style lang="less" scoped>
.side {
  position: absolute;
  right: 50px;
  top: 300px;
  width: 45px;
  height: 130px;
  background-color: #eae8eb;
  border-radius: 20px;
  text-align: center;
  overflow: hidden;
}
:nth-child(1) {
  padding: 10px 0;
  display: block;
  color: white;
  font-weight: bold;
  background-color: tomato;
  border-radius: 20px;
}
i {
  display: none;
}
:nth-child(3) {
  position: absolute;
  bottom: 20px;
  display: none;
  cursor: pointer;
  &:hover {
    color: tomato;
  }
}
</style>
